#include "emojidelegate.h"

#include <QPainter>

EmojiDelegate::EmojiDelegate(QObject *parent)
    : QAbstractItemDelegate{parent}
    , m_imageCache(300 * 1024 * 1024) // 300MB
{

}

// [1]
//void EmojiDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
//{
//    auto filePath = index.data().toString();
//    QImage image(filePath);
//    QRect rect = option.rect;
//    rect.adjust(1,1,-1,-1);
//    rect.moveCenter(option.rect.center());
//    painter->drawImage(rect, image);
//}

void EmojiDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto filePath = index.data().toString();
    const QString cacheKey = QString("%1_%2x%3").arg(filePath)
                                 .arg(option.rect.width())
                                 .arg(option.rect.height());

    QImage *cachedImage = m_imageCache.object(cacheKey);
    if (!cachedImage) {
        cachedImage = new QImage(filePath);
        int cost = cachedImage->sizeInBytes() / 1024 + 10; // KB为单位
        m_imageCache.insert(cacheKey, cachedImage, cost);
    }

    QRect rect = option.rect;
    rect.adjust(1,1,-1,-1);
    rect.moveCenter(option.rect.center());
    painter->drawImage(rect, *cachedImage);
}

QSize EmojiDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return QImage(index.data().toString()).scaledToHeight(80).size() +  QSize(4,4);
}
